<?php

namespace App\Models;

use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Laravel\Lumen\Auth\Authorizable;
use DateTimeInterface;

class Crm_Crowd_Apply extends Model implements AuthenticatableContract, AuthorizableContract
{
    use Authenticatable, Authorizable, HasFactory;

    /**
     * 关联到模型的数据表
     *
     * @var string
     */
    protected $table = 'crm_crowd_apply';

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'agencyid',
        'mid',
        'username',
        'mobile',
        'crowdid',
        'amount',
        'status'
    ];

    protected $appends = ['crowdName'];

    public function getCrowdNameAttribute()
    {
        if ($this->crowdid){
            return $this->hasOneCrowd->name;
        }else{
            return '';
        }
    }


    protected $hidden = [
        'is_del',
    ];

    public function scopeNodel($query)
    {
        return $query->where('is_del', 'N');
    }

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    public function hasOneMember()
    {
        return $this->hasOne('App\Models\Crm_Member', 'id', 'mid');
    }

    public function hasOneCrowd()
    {
        return $this->hasOne('App\Models\Crm_Crowd', 'id', 'crowdid');
    }

    public static function getFilter($filter)
    {
        return self::whereHas('hasOneMember',function ($query) use ($filter){
            if (isset($filter['username']) && !empty($filter['username'])) {
                $query->where('username', 'LIKE', '%'.$filter['username'].'%');
            }
            if (isset($filter['mobile']) && !empty($filter['mobile'])) {
                $query->where('mobile', 'LIKE', '%'.$filter['mobile'].'%');
            }
        })->where(function ($query) use ($filter){
            if (isset($filter['type']) && !empty($filter['type'])) {
                if($filter['type'] == 1){
                    $query->where('amount', '>', 0);
                }else{
                    $query->where('amount', 0);
                }
            }
            if (isset($filter['status']) && !empty($filter['status'])) {
                $query->where('status', $filter['status']);
            }
            $query->where('agencyid', $filter['aid']);
        })->orderBy('id', 'desc');
    }

}
